public class Main {
    public static void main(String[] args) {
        SolutionKMP solution = new SolutionKMP();
        System.out.println(solution.strStr("abeababeabf", "abeabf"));
        System.out.println(solution.strStr("sa1dbutsad", "sad"));
        System.out.println(solution.strStr("leetcode", "leeto"));
    }
}


class Solution {
    public int strStr(String haystack, String needle) {
        for (int i = 0; i < haystack.length() - needle.length() + 1; i++) {
            if (match(haystack, i, needle)) return i;
        }
        return -1;
    }


    boolean match(String str, int start, String target) {
        if (str.length() - start < target.length()) return false;
        for (int i = 0; i < target.length(); i++) {
            if (str.charAt(start + i) != target.charAt(i)) return false;
        }
        return true;
    }
}


class SolutionKMP {
    public int strStr(String haystack, String needle) {
        int[] next = getNext(needle);
        int i = 0;
        for (int j = 0; j < haystack.length(); j++) {
            while (i > 0 && haystack.charAt(j) != needle.charAt(i)) {
                i = next[i - 1];
            }
            if (haystack.charAt(j) == needle.charAt(i)) {
                i++;
                if (i == next.length) {
                    return j - next.length + 1;
                }
            }
        }
        return -1;
    }

    int[] getNext(String needle) {
        int[] next = new int[needle.length()];
        int i = 0, j = 1;
        while (j < needle.length()) {
            while (i > 0 && needle.charAt(i) != needle.charAt(j)) {
                i = next[i - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                i++;
            }
            next[j++] = i;
        }
        return next;
    }
}


//KMP
class Solution1 {
    public int strStr(String haystack, String needle) {
        int[] next = getNext(needle);
        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) {
                j = next[j - 1];
            }
            if (haystack.charAt(i) == needle.charAt(j)) {
                j++;
                if (j == needle.length()) {
                    return i - needle.length() + 1;
                }
            }
        }
        return -1;
    }

    private int[] getNext(String needle) {
        int[] next = new int[needle.length()];
        int i = 0;
        for (int j = 1; j < next.length; j++) {
            while (i > 0 && needle.charAt(i) != needle.charAt(j)) {
                i = next[i - 1];
            }
            if (needle.charAt(i) == needle.charAt(j)) {
                i++;
            }
            next[j] = i;
        }
        return next;
    }
}
